"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
import { useRouter } from "next/navigation"
import { toast } from "@/components/ui/use-toast"
import { loginUser, registerUser } from "@/lib/api-client"

interface User {
  id?: string
  username: string
  email?: string
  avatar?: string
}

interface AuthContextType {
  user: User | null
  isLoading: boolean
  login: (email: string, password: string) => Promise<void>
  register: (username: string, email: string, password: string) => Promise<void>
  logout: () => void
  isAuthenticated: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const router = useRouter()

  // Check if user is already logged in on mount
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem("token")
        const username = localStorage.getItem("username")
        const avatar = localStorage.getItem("avatar")

        if (token && username && avatar) {
          const newUser: User = { username: username, avatar: avatar };
          setUser(newUser)
        }
      } catch (error) {
        console.error("Authentication check failed:", error)
        // Token is invalid, remove it
        localStorage.removeItem("token")
        localStorage.removeItem("userId")
        localStorage.removeItem("username")
        localStorage.removeItem("avatar")
      } finally {
        setIsLoading(false)
      }
    }
    checkAuth()
  }, [])

  // Update the login function to store userId from the login response
  const login = async (email: string, password: string) => {
    try {
      setIsLoading(true)
      const data = await loginUser(email, password)

      // Save token and userId to localStorage
      localStorage.setItem("token", data.token)
      localStorage.setItem("userId", data.userId)
      localStorage.setItem("username", data.username)
      localStorage.setItem("avatar", data.avatar)
      const user: User = { username: data.username, avatar: data.avatar };
      setUser(user)

      toast({
        title: "登录成功",
        description: "欢迎回来！",
      })

      // Redirect to home page
      router.push("/")
    } catch (error) {
      console.error("Login error:", error)
      toast({
        title: "登录失败",
        description: error instanceof Error ? error.message : "请检查您的凭据并重试",
      })
    } finally {
      setIsLoading(false)
    }
  }

  const register = async (username: string, email: string, password: string) => {
    try {
      setIsLoading(true)
      await registerUser(username, email, password)

      toast({
        title: "注册成功",
        description: "请登录您的账户",
      })

      // Redirect to login page
      router.push("/login")
    } catch (error) {
      console.error("Registration error:", error)
      toast({
        title: "注册失败",
        description: error instanceof Error ? error.message : "请检查您的信息并重试",
      })
    } finally {
      setIsLoading(false)
    }
  }

  // Update logout to also clear userId
  const logout = () => {
    localStorage.removeItem("token")
    localStorage.removeItem("userId")
    setUser(null)
    router.push("/login")
    toast({
      title: "已退出登录",
      description: "您已成功退出登录",
    })
  }

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoading,
        login,
        register,
        logout,
        isAuthenticated: !!user,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
}

